<?php
declare(strict_types=1);
/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/10
 * Time: 11:25
 */
namespace App\Controller\User;

use App\Controller\AppBaseController;
use App\Model\Act;
use App\Model\ActAnswerJoin;
use App\Model\ActAnswerLog;
use App\Model\ActClockJoin;
use App\Model\ActJoin;
use App\Model\ActPrizeGoods;
use App\Model\ActPrizeJoin;
use App\Model\ActPush;
use App\Model\ActRead;
use App\Model\ActSurveyLog;
use App\Model\ActVoteJoin;
use App\Model\Notify;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\WxApiAuth;
use Hyperf\DbConnection\Db;

#[Controller(prefix: 'user')]
#[Middleware(WxApiAuth::class)]
class ActController extends AppBaseController
{

    /**
     * 活动中心列表
     * @param int $type  0：全部 1：答题 2：报名 3：抽奖 4：打卡 5：问卷 6：投票
     * @return object
     */
    #[RequestMapping(path:'actList/{type}',methods: 'get')]
    public function actList(int $type = 0): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where['status'] = 1;
            if(is_numeric($type) && $type!=0){
                $where['type'] = $type;
            }

//            if(in_array($type, [6])){
//                $pushWhere['act_type'] = $type;
//                $pushWhere['uid'] = $_user->id;
//                $pushList = ActPush::with(['act'=>function($query){
//                    $query->selectRaw('id,type,title,photo,start_time,end_time,status,created_at')->get();
//                }])->where($pushWhere)
//                    ->orderByDesc('id')
//                    ->offset($offset)
//                    ->limit($limit)
//                    ->get();
//                $list = [];
//                if($pushList->isNotEmpty()){
//                    foreach ($pushList as $key=>$value){
//                        $list[$key] = $value->act;
//                    }
//                }
//                $next = 0;
//                if($list){
//                    if(count($list)>$limit) $next = 1;
//                    foreach ($list as $key=>$value){
//                        if(time()<=strtotime($value->start_time)){
//                            $value->status = 0;
//                        }
//                        if(time()>strtotime($value->end_time)){
//                            $value->status = 2;
//                        }
//                    }
//                }
//            }else{
//                $list = Act::where($where)
//                    ->selectRaw('id,type,title,photo,start_time,end_time,status,created_at')
//                    ->orderByDesc('id')
//                    ->offset($offset)
//                    ->limit($limit)
//                    ->get();
//                $next = 0;
//                if($list->isNotEmpty()){
//                    if(count($list)>$limit) $next = 1;
//                    foreach ($list as $key=>$value){
//                        if(time()<=strtotime($value->start_time)){
//                            $value->status = 0;
//                        }
//                        if(time()>strtotime($value->end_time)){
//                            $value->status = 2;
//                        }
//                    }
//                }
//            }

            $uid = $_user->id;
            $list = Act::with(['actPush'=>function($query) use ($uid){
                        $query->where('uid',$uid)->selectRaw('id,uid,act_id')->get();
                    }])->where($where)
                        ->selectRaw('id,type,title,photo,start_time,end_time,status,created_at')
                        ->orderByDesc('id')
                        ->offset($offset)
                        ->limit($limit)
                        ->get();
            $next = 0;
            if($list->isNotEmpty()){
                if(count($list)>$limit) $next = 1;
                foreach ($list as $key=>$value){
                    if(time()<=strtotime($value->start_time)){
                        $value->status = 0;
                    }
                    if(time()>strtotime($value->end_time)){
                        $value->status = 2;
                    }
                }
            }

            return $this->reMsg->re(1,'success',['list' => $list, 'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 活动详情
     * @param int $act_id
     * @return object
     */
    #[RequestMapping(path:'actInfo/{act_id}',methods: 'get')]
    public function actInfo(int $act_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            //关联传值
            $uid = $_user->id;

            $intInfo = Act::where('id',$act_id)->first();
            if(empty($intInfo)) return $this->reMsg->re(10008);
            if($intInfo->type==1){
                //答题
                $info = Act::with(['answerJoinStatus'=>function($query) use ($uid){
                    $query->where('uid',$uid)->selectRaw('id,act_id,uid,answer_total_num,answer_true,answer_score,answer_score_up')->first();
                },'answerRule'=>function($query){
                    $query->selectRaw('id,act_id,rule,is_rank,limit_time')->first();
                }])->where('id',$act_id)->first();
            }else if($intInfo->type==3){
                //抽奖
                $info = Act::with(['prizeJoinStatus'=>function($query) use ($uid){
                    $query->where('uid',$uid)->selectRaw('id,act_id,uid,prize_goods_id,prize_goods_name,status')->first();
                },'prizeRule'=>function($query){
                    $query->selectRaw('id,act_id,rule,percent,template')->first();
                },'prizeGoods'=>function($query){
                    $query->selectRaw('id,act_id,name,photo,stock')->get();
                }])->where('id',$act_id)->first();
            }else if($intInfo->type==5){
                //问卷调查
                $info = Act::with(['joinStatus'=>function($query) use ($uid){
                    $query->where('uid',$uid)->selectRaw('id,act_id,uid')->first();
                },'surveyRule'=>function($query){
                    $query->selectRaw('id,act_id,rule')->first();
                }])->where('id',$act_id)->first();
            }else if($intInfo->type==6){
                //打卡
                $info = Act::with(['joinStatus'=>function($query) use ($uid){
                    $query->where('uid',$uid)->selectRaw('id,act_id,uid')->first();
                },'voteRule'=>function($query){
                    $query->selectRaw('id,act_id,rule,limit_num')->first();
                }])->where('id',$act_id)->first();
            }else{
                //报名
                $info = Act::with(['joinStatus'=>function($query) use ($uid){
                    $query->where('uid',$uid)->selectRaw('id,act_id,uid')->first();
                }])->where('id',$act_id)->first();
            }
            //处理 在线活动 通知
            $where['module'] = 3; //在线活动
            $where['relation_id'] = $act_id;
            $notifyInfo = Notify::where($where)->first();
            if($notifyInfo && $notifyInfo->status==0){
                $notifyInfo->status = 1;
                $notifyInfo->save();
            }
            return $this->reMsg->re(1,'success',$info);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }



    /**
     * 【报名】完成任务
     * @param int $act_id
     * @return object
     */
    #[RequestMapping(path: 'actJoin/{act_id}',methods: 'get')]
    public function actJoin(int $act_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            //获取所有参数
            $data = $this->request->all();

            $info = Act::where('id',$act_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            if(!in_array($info->type,[2,4])) return $this->reMsg->re(0,'活动类型有误');
            //判断开始时间
            if($info->start_time && time()<strtotime($info->start_time)) return $this->reMsg->re(0,'活动未开始');
            //判断结束时间
            if($info->end_time && time()>strtotime($info->end_time)) return $this->reMsg->re(0,'活动已结束');
            //判断参与人数
            if($info->max_limit>0 && $info->join_count>=$info->max_limit) return $this->reMsg->re(0,'参与人数超过限制');
            //判断报名信息收集
            if($info->type==2){
                if(!isset($data['collect_info']))  $data['collect_info']=null;
            }

            $data['party_id'] = $_user->party_id;
            $data['uid'] = $_user->id;
            $data['act_id'] = $info->id;
            $joinInfo = ActJoin::where($data)->first();
            if($joinInfo) return $this->reMsg->re(10010);

            Db::beginTransaction();

            $data['act_type'] = $info->type;
            $data['title'] = $info->title;
            $data['photo'] = $info->photo;
            $insertRet = ActJoin::create($data);
            if($insertRet){
                Act::where('id',$act_id)->increment('join_count',1); //学习人数加1
                //加积分
                $addType = 0;
                if($info->type==2) $addType = 6; //报名
//                if($info->type==4) $addType = 8; //签到打卡
                $params = [
                    'type'=> $addType, //积分类型 type 1:学习 2:评论 4:支部活动点赞 5:答题 6:报名 7:抽奖 8:签到打卡 9:问卷 10:支部信息更新
                    'action' => 1, //action 1:加积分 2:减积分
                    'uid' => $_user->id,  //用户id
                    'party_id' => $_user->party_id  //支部id
                ];
                $this->makeIntegralLog($params);
                Db::commit();
                return $this->reMsg->re(1);
            }else{
                Db::rollBack();
                return $this->reMsg->re(0);
            }
        }catch (\Exception $exception){
            Db::rollBack();
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 任务记录清楚
     * @param int $act_id
     * @return object
     */
    #[RequestMapping(path: 'actJoinClear/{act_id}',methods: 'get')]
    public function actJoinClear(int $act_id): object
    {
        try{
            return $this->reMsg->re(1);
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $info = Act::where('id',$act_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            $where['act_id'] = $act_id;
            $where['uid'] = $_user->id;

            //清除活动主记录
            ActJoin::where($where)->delete();

            if($info->type==1){
                //清除答题
                ActAnswerJoin::where($where)->delete();
                ActAnswerLog::where($where)->delete();
            }

            if($info->type==3){
                //清除抽奖
                ActPrizeJoin::where($where)->delete();
            }

            if($info->type==4){
                //清除打卡
                ActClockJoin::where($where)->delete();
            }

            if($info->type==6){
                //清除投票
                ActVoteJoin::where($where)->delete();
                ActVoteJoin::where('act_id',$act_id)->update(['vote_num'=>0]);
            }

            //减少活动参与数量
            if($info->join_count>0){
                $info->join_count = $info->join_count - 1;
                $info->save();
            }

            return $this->reMsg->re(1);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


}